/*
 * 文件名：MerchantCenterController.java
 * 版权：Copyright by hslt
 * 描述：
 * 修改人：yangfan
 * 修改时间：2016年7月21日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.shop.controller.merchantcenter;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSSClient;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.constants.ShopConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.upload.AliyunOssUtil;
import com.zcsy.commons.upload.FileUploadUtil;
import com.zcsy.commons.upload.FileUploadUtil.UploadFileItem;
import com.zcsy.commons.util.Globals;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.CommonVerifyCode;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.shop.service.system.ICommonTokenService;
import com.zcsy.manage.shop.service.system.ICommonVerifyCodeService;
import com.zcsy.manage.shop.service.system.ISUserService;

/**
 * @Title: NewsController.java
 * @Package： com.hslt.manage.distribution.controller.news
 * @Description:我的控制层
 * @author yangfan 373188993@qq.com
 * @Copyright: 2016 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月30日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value = "shopMine")
public class MerchantCenterController {
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private ICommonTokenService commonTokenService;
    
    @Autowired
    private ISUserService suserService;
    
    @Autowired
    private ICommonVerifyCodeService commonVerifyCode;
    
    private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");
    private static String endpoint = propertiesUtil.getProperty("OSS_ENDPOINT");
    private static String accessId= propertiesUtil.getProperty("ACCESS_ID");
    private static String accessKey= propertiesUtil.getProperty("ACCESS_KEY");
    private static String bucketName= propertiesUtil.getProperty("bucketName");
    
    /**
     * @Description 修改个人信息
     * @param token
     *        id       主键id
     *        userName 姓名
     *        nickName 昵称
     *        sex      性别
     * @return result
     * @author yangfan 373188993@qq.com
     * @date 2016年6月30日
     */
    @RequestMapping(value = "changePersonInfo")
    @ResponseBody
    public RequestJson changePersonInfo(String token ,String id , String userName , String nickName , Integer sex ) {

        RequestJson result = new RequestJson();
        
        try {
            //设置修改信息
            User user = new User();
            user.setUsername(userName);
            user.setNickname(nickName);
            user.setSex(sex);
            user.setId(id);
            
            int flag = userService.updateByPrimaryKeySelective(user);
            
            if (flag == ShopConstants.UPDATE_SUCCESS) {
                result.setSuccess(true);
                result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
                result.setMsg("信息修改成功！");
                user = userService.selectByPrimaryKey(id);
                result.setObj(user);
            } else {
                result.setSuccess(false);
                result.setResultCode(ShopConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("信息修改失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;

    }
    
    /**
     * @Description 上传头像接口 <br>
     * 1、…<br>
     * 2、…<br>
     * 
     * @param token
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月7日
     * @see 
     */
    @RequestMapping(value = "uploadHeadPic", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson uploadHeadPic(String token,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        Integer fileId = 0;

        try {
             OSSClient client = new  OSSClient(endpoint,accessId,accessKey); 
//            res.setContentType("text/html");
            final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(req);

            File file = uploadFiles[0].getInternalFile();

          //图片上传至阿里云服务器
            Map<String, Object> returnmap = AliyunOssUtil.uploadFile(client,bucketName, file.getName(),file); 
            String headimgUrl = (String)returnmap.get("objectkey");
            
          //通过token获取用户信息
            CommonToken tokenInfo = commonTokenService.selectByToken(token);
            String loginname = tokenInfo.getAccount();
            User user = userService.selectByLoginName(loginname);
            
            if(user != null){
                user.setHeadimg(headimgUrl);
                int flag = userService.updateByPrimaryKeySelective(user);
                if(flag == Constants.SQL_RESULT_SUCCESS){
                    result.setResultCode(ShopConstants.RESULT_CODE_SUCCESS);
                    result.setMsg("头像上传成功！");
                    result.setObj(user);
                }else {
                    result.setResultCode(ShopConstants.RESULT_CODE_FALSE);
                    result.setMsg("头像上传失败！");
                }
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        
        return result;
        
    }
    
    /**
     * @Method: updatePassword
     * @Description 修改密码
     * @param opwd
     *            原始密码
     * @param token
     * @param npwd
     *            新密码
     * @return
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月27日
     * @see
     */
    @RequestMapping(value = "updatePassword")
    @ResponseBody
    public RequestJson updatePassword(String opwd, String token, String npwd) {

        RequestJson result = new RequestJson();

        try {
            CommonToken tokenInfo = commonTokenService.selectByToken(token);
            // 根据token查询登录名
            String loginname = tokenInfo.getAccount();
            
            if (StringUtils.isNotEmpty(loginname)) {
                String spwd = userService.selectByLoginName(loginname).getPwd();
                
                // 如果原始密码输入正确
                if (spwd.equals(opwd)) {
                    Date date = new Date();
                    User user = new User();
                    user.setModifydatetime(date);
                    user.setPwd(npwd);
                    user.setLoginname(loginname);
                    suserService.changePwd(user);
                    
                    result.setSuccess(true);
                    result.setResultCode(ShopConstants.MODIFY_PASSWORD_SUCCESS);
                    result.setMsg("修改成功！");
                    
                } else {
                    result.setSuccess(false);
                    result.setMsg("原密码输入错误！");
                    result.setResultCode(ShopConstants.OLD_PASSWORD_FALSE);
                    
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;
    }
    
    /**
     * @Method: boundPhone
     * @Description 绑定手机
     * @param token
     * @param phone 手机号
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月27日
     * @see 
     */
    @RequestMapping(value = "boundPhone" )
    @ResponseBody
    public RequestJson boundPhone(String code , String token, String phone) {
        RequestJson result = new RequestJson();
        
        commonTokenService.OrderInteractState(token , result);
        if (result.isSuccess()) {
            CommonToken tokenInfo = commonTokenService.selectByToken(token);
            // 根据token获得用户名
            String loginname = tokenInfo.getAccount();
            
            CommonVerifyCode verifyCode = commonVerifyCode.selectCodeByAccount(loginname);
            // 获得数据库里的验证码
            String codes = verifyCode.getCode();
            Date expireTime = verifyCode.getExpireTime();
            Date date = new Date();
            
            if ((date.compareTo(expireTime))<0) {
                if (code.equals(codes)) {
                    // 如果手机号不存在于数据库中
                    if ((suserService.selectUserIfPhoneExists(phone, ShopConstants.OWNER_USER_TYPE)
                            .size() == 0)){
                        suserService.boundPhone(phone, loginname);
                        result.setMsg("绑定成功！");
                        result.setResultCode(ShopConstants.PHONE_BIND_SUCCESS);
                        result.setSuccess(true);
                        
                    } else {
                        result.setMsg("该手机已被占用，请重新输入！");
                        result.setResultCode(ShopConstants.PHONE_ALREADY_BIND);
                        result.setSuccess(true);

                    }
                    
                }else {
                    result.setMsg("输入验证码有误！");
                    result.setSuccess(false);
                    result.setResultCode(ShopConstants.CODE_IS_FALSE);
                    
                }
                
            }else{
                result.setMsg("验证码失效");
                result.setResultCode(ShopConstants.CODE_IS_INVALIDE);
                result.setSuccess(false);
                
            }
                
        }
        
        return result;
    }
}
